interface JProps {
  scriptUrl: string
  globalVarName: string
}

const RemoteComponentLoader = (props: JProps) => {
  const { scriptUrl, globalVarName } = props
  const [CusComponent, setCusComponent] = useState<any>(null)
  const [error, setError] = useState<any>(null)

  useEffect(() => {
    const script = document.createElement('script')
    script.src = scriptUrl
    script.async = true

    script.onload = () => {
      // UMD模块通常会暴露在全局变量中
      const component = (window as any)[globalVarName]
      if (component) {
        setCusComponent(() => component.default || component)
      } else {
        setError(`全局变量 ${globalVarName} 未找到`)
      }
    }

    script.onerror = () => {
      setError(`无法加载脚本: ${scriptUrl}`)
    }

    document.body.appendChild(script)

    return () => {
      document.body.removeChild(script)
      // 清理全局变量
      if (window[globalVarName]) {
        delete window[globalVarName]
      }
    }
  }, [scriptUrl, globalVarName])

  if (error) {
    return <div className='error'>{error}</div>
  }

  if (!CusComponent) {
    return <div className='loading'>加载组件中...</div>
  }

  return <CusComponent />
}

export default RemoteComponentLoader
